import { Inject, Provide, Logger } from '@midwayjs/core';
import { LoginDTO, RegisterDTO } from '../dto/user.dto';
import { JwtService } from '@midwayjs/jwt';
import { compare, hash } from 'bcryptjs';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { User } from '../entity/user';
import { ILogger } from '@midwayjs/logger';
import { AnalyticsService } from './analytics.service';

@Provide()
export class UserService {
  @Logger()
  logger: ILogger;

  @Inject()
  jwtService: JwtService;

  @Inject()
  analyticsService: AnalyticsService;

  @InjectEntityModel(User)
  userModel: Repository<User>;

  /**
   * 用户登录
   * @param loginDTO 登录信息
   */
  async login(loginDTO: LoginDTO) {
    const { username, password } = loginDTO;
    
    this.logger.info(`[UserService] 用户登录请求: ${username}`);

    // 查找用户
    const user = await this.userModel.findOneBy({ username });
    if (!user) {
      this.logger.warn(`[UserService] 登录失败: 用户不存在 ${username}`);
      throw new Error('用户不存在');
    }

    // 验证密码
    const isValid = await compare(password, user.password);
    if (!isValid) {
      this.logger.warn(`[UserService] 登录失败: 密码错误 ${username}`);
      throw new Error('密码错误');
    }

    // 生成 JWT token
    const token = await this.jwtService.sign({
      id: user.id,
      username: user.username,
      email: user.email
    });

    this.logger.info(`[UserService] 用户登录成功: ${username}`);
    
    // 埋点：记录用户登录事件
    await this.analyticsService.trackUserLogin(user.id, user.username);

    return {
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    };
  }

  /**
   * 用户注册
   * @param registerDTO 注册信息
   */
  async register(registerDTO: RegisterDTO) {
    const { username, password, email } = registerDTO;
    
    this.logger.info(`[UserService] 用户注册请求: ${username}`);

    // 检查用户名是否已存在
    const existingUser = await this.userModel.findOneBy({ username });
    if (existingUser) {
      this.logger.warn(`[UserService] 注册失败: 用户名已存在 ${username}`);
      throw new Error('用户名已存在');
    }

    // 加密密码
    const hashedPassword = await hash(password, 10);

    // 创建新用户
    const newUser = this.userModel.create({
      username,
      password: hashedPassword,
      email: email || '',
      status: true
    });
    
    await this.userModel.save(newUser);
    
    this.logger.info(`[UserService] 用户注册成功: ${username}`);

    // 生成 JWT token
    const token = await this.jwtService.sign({
      id: newUser.id,
      username: newUser.username,
      email: newUser.email
    });
    
    // 埋点：记录用户注册事件
    await this.analyticsService.trackUserRegistration(newUser.id, newUser.username, newUser.email);

    return {
      token,
      user: {
        id: newUser.id,
        username: newUser.username,
        email: newUser.email
      }
    };
  }
  
  /**
   * 根据ID获取用户信息
   * @param id 用户ID
   */
  async getUserById(id: number) {
    this.logger.info(`[UserService] 获取用户信息请求: ${id}`);
    return await this.userModel.findOneBy({ id });
  }
  
  /**
   * 获取所有用户
   */
  async getAllUsers() {
    this.logger.info('[UserService] 获取所有用户请求');
    return await this.userModel.find();
  }
}